<template>
  <view class="container">
    <hello-title></hello-title>
    <view style="height: 24px"></view>
    <view class="page-title page-title--no-padding">血糖</view>
    <view class="page-title page-title--sub page-title--no-padding">{{
        latestData && formatDate(latestData.measurementDate)
      }}
    </view>
    <view class="heavy-text">
      <text class="heavy-text__title">{{ latestData && latestData.glucoseConcentration }}</text>
      <text class="heavy-text__unit">mmol/L</text>
    </view>
    <view v-if="waringText" class="waring">{{ waringText }}</view>
    <view class="page-title page-title--no-padding">血糖趋势图</view>
    <view class="line-card">
      <view class="line-card__tabs">
        <view class="line-card__tab line-card__tab--active-red">
          空腹
        </view>
      </view>
      <view class="line-card__content" :class="{'line-card__content--hidden':isCreateActionSheetOpen}">
        <line-chart id="blood-sugar-month" v-if="monthChartData" :config="monthChartData"
                    line-color="#ED7D76"></line-chart>
      </view>
    </view>
    <view class="page-title page-title--no-padding">最近异常数据</view>
    <view class="data-card-area">
      <view class="data-card data-card--red" v-for="(item,index) in warningValues" :key="index">
        <view class="data-card__head">
          <text>{{ formatDate(item.measurementDate, "MM-DD HH:mm") }}</text>
          <view class="data-card__icon data-card__icon--warning"></view>
        </view>
        <view class="data-card__content">
          <view>
            <text style="font-size: 24px">{{ item.glucoseConcentration }}</text>
            <text class="unit">mmol/L</text>
          </view>
          <text class="tag_text tag_text--red tag_text--round">{{getName(item.mealPeriod)}}</text>
        </view>
      </view>
    </view>
    <view class="page-title page-title--no-padding">历史血糖数据</view>
    <view v-for="record in historyRecord" :key="record.measurementDate">
      <view class="data-card data-card--red margin-v--normal">
        <view class="data-card__head">
          <view>
            <text class="tag_text tag_text--red tag_text--round">{{getName(record.mealPeriod)}}</text>
            <view class="width-spacer"></view>
            <text>{{ formatDate(record.measurementDate) }}</text>
          </view>
          <view class="data-card__icon data-card__icon--blood"></view>
        </view>
        <view class="data-card__content">
          <text>{{ record.glucoseConcentration }}</text>
          <text class="unit">mmol/L</text>
        </view>
      </view>
    </view>
    <view class="height-spacer"></view>
    <!--    添加数据-->
    <view class="margin-v--normal fix-bottom">
      <button class="button--block button--purple" @tap="showCreateActionSheet">添加数据</button>
    </view>
    <!--    modal/底部操作栏-->
    <AtModal :isOpened="isCreateActionSheetOpen" :onClose="closeCreateActionSheet" v-if="isCreateActionSheetOpen">
      <AtModalContent>
        <view>
          <picker
            mode='selector'
            :range="bloodSugarTypeRange"
            range-key="name"
            :value="bloodSugarType"
            @change="handleBloodSugarTypeInputChange"
          >
            <view class='input-row'>
              <view class='input-row__label'>类型</view>
              <view class='input-row__content'>{{ getName(bloodSugarType) }}</view>
            </view>
          </picker>
        </view>
        <view class='input-row'>
          <view class='input-row__label'>数值</view>
          <view class='input-row__content'><input v-model="valueInput" type="digit" placeholder="mmol/L"/></view>
        </view>
      </AtModalContent>
      <AtModalAction>
        <button @tap="addRecord" class="custom-button">确定</button>
      </AtModalAction>
    </AtModal>
  </view>
</template>

<script>
import "./index.less";
import helloTitle from "../../../common-components/hello-title/hello-title";
import {getHistoryData, updateBloodSugars} from "../../../services/healthy-data-service";
import {AtModal, AtModalHeader, AtModalContent, AtModalAction} from 'taro-ui-vue'
import findIndex from 'lodash.findindex';
import get from 'lodash.get';
import LineChart from "../../../common-components/line-chart/line-chart"

const {getUserProfileDataToday} = require("../../../services/healthy-data-service");
import dayjs from 'dayjs';

/**
 *
 glucoseConcentration: 72
 level: 1
 levelName: 2
 mealPeriod: 13
 mealPeriodName: null
 measurementDate: 1631362833524
 }
 */


const formatChartData = (data, daysNumber: number, valueGetter: (recordValue)=>{ value: number }, yAxisConfig) => {
  const baseConfig = {
    yAxis: yAxisConfig ? yAxisConfig : {
      unit: 1,
      base: 50,
      top: 140,
      display: [
        // 必须按顺序
        {value: 50, label: "50"},
        {value: 90, label: "90"},
        {value: 120, label: "120"},
        {value: 140, label: "140"},
      ],
    },
    dataset: [],
  }
  for (let i = 1; i <= daysNumber; i++) {
    const index = findIndex(data, (item) => {
      return item.dayOfWeek === i
    });
    baseConfig.dataset.push(valueGetter(data[index]))
  }
  return baseConfig;
}

export default {
  name: "index",
  components: {
    helloTitle, LineChart,
    AtModal, AtModalContent, AtModalAction
  },
  data() {
    return {
      recordList: [],
      isCreateActionSheetOpen: false,
      renalInputType: '尿酸',
      renalInputValue: '',
      latestData: null,
      historyRecord: [],
      monthChartData: null,
      dateInput: "",
      bloodSugarType: "",
      valueInput: "",
      warningValues: [],
      bloodSugarTypeRange: [
        {
          id: 0,
          name: '空腹'
        },
        {
          id: 1,
          name: '早餐后'
        },
        {
          id: 2,
          name: '午餐前'
        },
        {
          id: 3,
          name: '午餐后'
        },
        {
          id: 4,
          name: '晚餐前'
        },
        {
          id: 5,
          name: '晚餐后'
        },
        {
          id: 6,
          name: '睡前'
        },
        {
          id: 11, //7
          name: '凌晨'
        },
        {
          id: 12, //8
          name: '餐前'
        },
        {
          id: 13,//9
          name: '餐后2小时'
        },
        {
          id: 14,//10
          name: '运动前'
        },
        {
          id: 15, //11
          name: '运动后'
        },
        {
          id: 16, //12
          name: '随机'
        },
      ]
    }
  },
  computed: {
    waringText() {
      if (!this.latestData) {
        return '';
      }

      const { glucoseConcentration, mealPeriod } = this.latestData;
      if (mealPeriod.toString() === '0') {
        return this.getWaringTextByLimosis(glucoseConcentration);
      }

      if (mealPeriod.toString() === '13') {
        return this.getWaringTextByEatingAfterTwoHours(glucoseConcentration);
      }
      return '';
    }
  },
  methods: {
    async addRecord() {
      console.log(`${this.dateInput} ${this.timeInput}`);
      await updateBloodSugars({
        mealPeriod: this.bloodSugarType,
        glucoseConcentration: this.valueInput,
        measurementDate: Date.now(),
      })
      await this.initData();
    },
    showCreateActionSheet() {
      this.isCreateActionSheetOpen = true;
    },
    closeCreateActionSheet() {
      this.isCreateActionSheetOpen = false;
    },
    handleBloodSugarTypeInputChange(e) {
      if(e.detail.value == "7"){
        this.bloodSugarType = "11";
        return;
      }
      if(e.detail.value == "8"){
        this.bloodSugarType = "12";
        return;
      }
      if(e.detail.value == "9"){
        this.bloodSugarType = "13";
        return;
      }
      if(e.detail.value == "10"){
        this.bloodSugarType = "14";
        return;
      }
      if(e.detail.value == "11"){
        this.bloodSugarType = "15";
        return;
      }
      if(e.detail.value == "12"){
        this.bloodSugarType = "16";
        return;
      }
      this.bloodSugarType = e.detail.value;
    },
    formatDate(timestamp, format) {
      if (!format) {
        format = "YYYY-MM-DD HH:mm"
      }
      return dayjs(timestamp).format(format);
    },
    getName(key) {
      console.log("血糖选择:",key)
      key = key.toString();
      switch (key) {
        case "0":
          return "空腹";
          break;
        case "1":
          return "早餐后";
          break;
        case "2":
          return "午餐前";
          break;
        case "3":
          return "午餐后";
          break;
        case "4":
          return "晚餐前";
          break;
        case "5":
          return "晚餐后";
          break;
        case "6":
          return "睡前";
          break;
        case "11":
          return "凌晨";
          break;
        case "12":
          return "餐前";
          break;
        case "13":
          return "餐后2小时";
          break;
        case "14":
          return "运动前";
          break;
        case "15":
          return "运动后";
          break;
        case "16":
          return "随机";
          break;
        case "100":
          return "空腹";
        case "101":
          return "餐后";
          break;
        default:
          return "--";
          break;
      }
    },
    async initData() {
      this.isCreateActionSheetOpen = false;
      const recordList = await getHistoryData("DAY_OF_MONTH", "BLOOD_SUGAR");
      const latestData = await getUserProfileDataToday();
      this.historyRecord = recordList.flatMap(day => {
        const valuesInDay = get(day, "value", []) ? get(day, "value", []) : [];
        return valuesInDay
      }).reverse()
      // 遍历每天的数据
      const dataForKongfuChart = recordList.map(day => {
        // 每天有 N 条数据,从 N 条数据找出该条数据是否为空腹血糖
        // 只筛选出空腹记录
        const valuesInDay = get(day, "value", []) ? get(day, "value", []) : [];
        const kongfuData = valuesInDay.filter(recordInDay => recordInDay.mealPeriod == 0);
        return {
          ...day,
          value: kongfuData.length ? kongfuData[0] : null // kongfuData是个数组,拿第一条或者返回 null 就行
        }
      })
      console.log("血糖页面全量信息查询", latestData);
      console.log("血糖健康记录:", this.recordList);
      console.log("血糖健康记录,用于构建空腹血糖折线图的数据", dataForKongfuChart);
      const yAxisConfig = {
        unit: 1,
        base: 0,
        top: 35,
        display: [
          // 必须按顺序
          {value: 0, label: "0"},
          {value: 4, label: "4"},
          {value: 6, label: 6},
          {value: 10, label: 10},
          {value: 14, label: 14},
        ],
      }
      const monthChartData = formatChartData(dataForKongfuChart, 30, (item) => {
        return {value: get(item, "value.glucoseConcentration", 0)}
      }, yAxisConfig)
      this.monthChartData = monthChartData;
      console.log(this.monthChartData)
      // 拿到最新数据
      this.latestData = get(latestData, "data.data.bodyProfile.bloodSugars[0]");
      console.log(this.latestData);
      // 需要警惕的血糖
      const warningValues = get(latestData, "data.data.bodyProfile.bloodSugarInfo")
      console.log(warningValues);
      this.warningValues={}
      if(warningValues.hasOwnProperty(100)){
        console.info("100")
        this.warningValues[100]=warningValues[100]
      }
      if(warningValues.hasOwnProperty(101)){
        console.info("101")
        this.warningValues[101]=warningValues[101]
      }
      console.log("需要警惕的须糖", this.warningValues);
    },
    getWaringTextByLimosis(glucoseConcentration) {
      if (glucoseConcentration < 3.9) {
        return '警告：您的血糖偏低，建议及时补充糖分'
      }

      if (glucoseConcentration > 6.2) {
        return '警告：您的血糖偏高，建议控糖管理'
      }

      return ''
    },
    getWaringTextByEatingAfterTwoHours(glucoseConcentration) {
      if (glucoseConcentration < 7.8) {
        return '警告：您的血糖偏低，建议及时补充糖分'
      }

      if (glucoseConcentration > 9) {
        return '警告：您的血糖偏高，建议控糖管理'
      }

      return ''
    }
  },
  async created() {
    await this.initData();
  }
}
</script>
